package cn.iocoder.yudao.module.ai.utils.sm.sm3;
import cn.iocoder.yudao.module.ai.utils.sm.GMBaseUtil;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

import java.util.Arrays;
public class SM3Util extends GMBaseUtil implements MacCodeUtils {

    public SM3Util() {
    }

    public SM3Util(String key) {
    }

    public static void main(String[] args) throws Exception {


        String cKey = "12345678901234as";
        SM3Util hmac = new SM3Util();
        // 需要加密的字串
        String cSrc = "515ad5285833e6d15c1f488055d26389a181e11536312a16ad8fcfd992cc0a6b94f5f97a02a9cb66b64a31afd1acd17a6bb20c339f5a2260f33c9fa23bb6a8fc0dd3a232288c6fbd2b431886a762a0e6";

        System.out.println(cSrc);
        // 加密
        String enString = hmac.getSign(cSrc);
        System.out.println("加密后的字串是：" + enString);
        System.out.println("验证结果：" + hmac.infoverify(enString,cSrc));
    }
    @Override
    public String getSign(String con ) throws Exception{
        byte[] content = con.getBytes("utf-8");
        return new Base64().encodeToString(hash(content));
    }
    @Override
    public boolean infoverify(String sign ,String con)throws Exception{
        byte[] content = con.getBytes("utf-8");
        byte[] signature =  new Base64().decode(sign);
        return verify(content,signature) ;
    }

    /**
     * 计算SM3摘要值
     *
     * @param srcData 原文
     * @return 摘要值，对于SM3算法来说是32字节
     */
    public static byte[] hash(byte[] srcData) {
        SM3Digest digest = new SM3Digest();
        digest.update(srcData, 0, srcData.length);
        byte[] hash = new byte[digest.getDigestSize()];
        digest.doFinal(hash, 0);
        return hash;
    }

    /**
     * 验证摘要
     *
     * @param srcData 原文
     * @param sm3Hash 摘要值
     * @return 返回true标识验证成功，false标识验证失败
     */
    public static boolean verify(byte[] srcData, byte[] sm3Hash) {
        byte[] newHash = hash(srcData);
        if (Arrays.equals(newHash, sm3Hash)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 计算SM3 Mac值
     *
     * @param key     key值，可以是任意长度的字节数组
     * @param srcData 原文
     * @return Mac值，对于HMac-SM3来说是32字节
     */
    public static byte[] hmac(byte[] key, byte[] srcData) {
        KeyParameter keyParameter = new KeyParameter(key);
        SM3Digest digest = new SM3Digest();
        HMac mac = new HMac(digest);
        mac.init(keyParameter);
        mac.update(srcData, 0, srcData.length);
        byte[] result = new byte[mac.getMacSize()];
        mac.doFinal(result, 0);
        return result;
    }
}
